package cn.tips.dmp.supports.util;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import okhttp3.*;

import java.io.IOException;
import java.util.Map;
import java.util.concurrent.TimeUnit;

public class ThirdHttpUtil {
	public static String get(String url, Map<String, String> params, Map<String, String> head) throws Exception {
		if (null == url) throw new NullPointerException("Url == null");
		String getUrl = buildGetUrl(url, params);
		Request.Builder reqBuilder = new Request.Builder();
		if (null != head) {
//            head.forEach((k, v) -> reqBuilder.addHeader(k, v)); jdk 1.8
			for (String name : head.keySet()) {   //jdk1.7
				String value = head.get(name);
				reqBuilder.addHeader(name,value);
			}
		}
		reqBuilder.url(getUrl);
		return doCall(reqBuilder.build(), getUrl);

	}

	public static String postJson(String url, Map<String, String> params, Map<String, String> head) throws Exception {
		if (null == url) throw new NullPointerException("Url == null");
		Request.Builder reqBuilder = new Request.Builder();
		if (null != head) {
			head.forEach((k, v) -> reqBuilder.addHeader(k, v)); //jdk 1.8
		}
		System.out.println("请求体：" + JSON.toJSONString(params));
		RequestBody requestBody = RequestBody.create(MediaType.parse("application/json; charset=utf-8"), JSON.toJSONString(params));
		reqBuilder.url(url).post(requestBody);

		return doCall(reqBuilder.build(), url);
	}

	public static String postForm(String url, Map<String, String> params, Map<String, String> head) throws Exception {
		if (null == url) throw new NullPointerException("Url == null");
		Request.Builder reqBuilder = new Request.Builder();
		if (null != head) {
			head.forEach((k, v) -> reqBuilder.addHeader(k, v)); //jdk 1.8
		}
		FormBody.Builder formBuilder = new FormBody.Builder();
		if (null != params) {
			params.forEach((k, v) -> formBuilder.add(k, v)); //jdk 1.8
		}
		reqBuilder.url(url).post(formBuilder.build());
		String result = doCall(reqBuilder.build(), url);
		return result;
	}

	private static String doCall(Request request, String url) throws Exception {
//		OkHttpClient okHttpClient = new OkHttpClient();
		OkHttpClient okHttpClient = new OkHttpClient.Builder()
				.connectTimeout(30, TimeUnit.SECONDS)//连接超时(单位:秒)
//				.callTimeout(120, TimeUnit.SECONDS)//整个流程耗费的超时时间(单位:秒)--很少人使用
				.pingInterval(5, TimeUnit.SECONDS)//websocket轮训间隔(单位:秒)
				.readTimeout(60, TimeUnit.SECONDS)//读取超时(单位:秒)
				.writeTimeout(60, TimeUnit.SECONDS)//写入超时(单位:秒)
				.build();

		Call call = okHttpClient.newCall(request);
		try {
			Response response = call.execute();
			if (!response.isSuccessful()) {
				throw new Exception("post " + url + " return error http status " + response.code());
			}
			return response.body().string();
		} catch (IOException e) {
			e.printStackTrace();
			throw new Exception("post " + url + " error", e);
		}
	}

	private static String buildGetUrl(String url, Map<String, String> params) {
		if (null == params || url == null) return url;
		StringBuilder sb = new StringBuilder(url);
		int index = url.indexOf("?");
		if (index == -1) {
			sb.append("?");
		} else if (index > 0 && index < url.length() - 1) {
			if (!url.endsWith("&")) {
				sb.append("&");
			}
		} else {
			//?结尾，不做处理
		}
//        params.forEach((k, v) -> sb.append(k).append("=").append(v).append("&")); jdk1.8
		for (String name : params.keySet()) {   //jdk1.7
			String value = params.get(name);
			sb.append(name).append("=").append(value).append("&");
		}
		if (params.size() > 0) {
			sb.deleteCharAt(sb.length() - 1);
		}
		return sb.toString();
	}

	/**
	 * 处理返回结果
	 * @param responseBody
	 * @return
	 * @throws Exception
	 */
	public static String getResult(String responseBody) throws Exception{
		// 返回结果解析
		JSONObject userObj = JSON.parseObject(responseBody);
		// 返回errno为0，表示成功，其他表示失败
		System.out.println(userObj.toJSONString());
		if (userObj.getIntValue("errorCode") == 200000) {
			JSONObject data = userObj.getJSONObject("data");
			if (data != null) {
				return data.toString();
			}
			return null;
		} else {
			throw new Exception(userObj.getIntValue("errorCode") + ":"
					+ userObj.getString("msg"));
		}
	}
}
